#!/usr/bin/env python
########################################################################
#  Quote - On-line historical quotes
#  Copyright (C) 2007,8 Ofer Barkai
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
########################################################################
"""Retrieve historical FX from Bank-Of-Israel """
import urllib
import re
import quote

boiCur = { # curency-code:(BOI-code, start-date)
    'BIB':('_77','19860801'), 'USD':('_01','19771031'),
    'GBP':('_02','19771031'), 'JPY':('_31','19771031'),
    'EUR':('_27','19990104'), 'ATS':('_21','19771031'),
    'BEF':('_04','19771031'), 'FIM':('_07','19771031'),
    'FRF':('_22','19771031'), 'DEM':('_08','19771031'),
    'IEP':('_09','19840111'), 'ITL':('_16','19771031'),
    'NLG':('_15','19771031'), 'ESP':('_19','19840111'),
    'AUD':('_18','19771031'), 'CAD':('_06','19771031'),
    'DKK':('_12','19771031'), 'NOK':('_28','19771031'),
    'ZAR':('_17','19771031'), 'SEK':('_03','19771031'),
    'CHF':('_05','19771031'), 'JOD':('_69','19771031'),
    'LBP':('_70','19771031'), 'EGP':('_79','19821125')
}

def get(symbol, d1, d2):
    '''Retrieve ILS rates from www.boi.gov.il when available'''
    if len(symbol) != 8 or not symbol.endswith('ILS=X') or \
       not symbol[0:3] in boiCur:
        raise Exception('symbol not supported by BOI')
    if d1 < boiCur[symbol[0:3]][1]:
        raise Exception('date not supported by BOI')
    quote.info("boi.get(%s, %s, %s)", symbol, d1, d2)
    url = 'http://www.boi.gov.il/eng.shearim/select_cur/cur4sdh.php'
    query = (
        ('curname[]', boiCur[symbol[0:3]][0]),
        ('curfile', 'htm'),
        ('fyear', d1[0:4]),
        ('fmonth', d1[4:6]),
        ('fday', d1[6:8]),
        ('lyear', d2[0:4]),
        ('lmonth', d2[4:6]),
        ('lday', d2[6:8]),
        ('whosend', 'tvach')
    )
    url=url+'?'+urllib.urlencode(query)
    page = urllib.urlopen(url).read().splitlines()
    result = {}
    for line in page:
        if line.find("'Week day:") > 0:
            day, month, year, rate = re.match(
                r'^.*>(\d\d)-(\d\d)-(\d\d\d\d)<.*>([0-9.]+)<.*$', line).groups()
            result[year+month+day] = {'rate':rate}
    return result

